<?php
class UploadAction extends CAction
{
    public $field_name = 'file';
    public $from = 'normal';
    public $bucket = 'default';//keep it for new feature
    public $result = array();
    private $errmsg = null;
    private $_response = array();

    private function _buildResp()
    {
        $this->result = array();
        switch ($this->from) {
            case 'xheditor':
                if (is_null($this->errmsg)) {
                    $this->result = $this->_response;
                    $this->result['msg'] = Yii::app()->storage->getPreviewUrl($this->_response['key'], $this->bucket);
                    $this->result['err'] = '';
                } else {
                    $this->result['err'] = $this->errmsg;
                    $this->result['msg'] = $this->errmsg;
                }
                break;
            default:
                if (is_null($this->errmsg)) {
                    $this->result = $this->_response;
                    $this->result['url'] = Yii::app()->storage->getPreviewUrl($this->_response['key'], $this->bucket);
                } else {
                    $this->result['error'] = $this->errmsg;
                }
                break;
        }
    }

    public function run()
    {
        $this->from = Yii::app()->request->getQuery('from', 'normal');
        $this->field_name = Yii::app()->request->getQuery('field', $this->field_name);
        $this->bucket = Yii::app()->params['wxyun_bucket'];
        $path = Yii::app()->request->getQuery('path', '/sliders');

        if (isset($_FILES[$this->field_name])) {
            $file = $_FILES[$this->field_name];
            $this->_response = Yii::app()->storage->upload($file['tmp_name'], $path, $file['name'], '', $this->bucket);
            if (empty($this->_response)) {
                $this->errmsg = '上传出错';
            }
        } else {
            $this->errmsg = '请上传文件';
        }
        $this->_buildResp();
        header('Content-Type: application/json');
        echo CJSON::encode($this->result);
    }
}
